package com.ruoyi.loan.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.loan.domain.CustomerAllocation;
import com.ruoyi.loan.domain.CustomerInfo;
import com.ruoyi.loan.domain.CustomerNeed;
import com.ruoyi.loan.domain.CustomerSnapshot;
import com.ruoyi.loan.domain.reponse.CustomerFollowResponse;
import com.ruoyi.loan.domain.reponse.CustomerInfoResponse;
import com.ruoyi.loan.domain.request.CustomerInfoRequest;
import com.ruoyi.loan.domain.request.CustomerRequest;
import com.ruoyi.loan.service.ICustomerAllocationService;
import com.ruoyi.loan.service.ICustomerInfoService;
import com.ruoyi.loan.service.ICustomerNeedService;
import com.ruoyi.loan.service.ICustomerSnapshotService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户Controller
 *
 * @author ruoyi
 * @date 2023-03-18
 */
@Slf4j
@RestController
@RequestMapping("/customerInfo")
public class CustomerInfoController extends BaseController {

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private ICustomerNeedService customerNeedService;

    @Autowired
    private ICustomerAllocationService customerRemarkService;

    @Autowired
    private ICustomerSnapshotService customerSnapshotService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询客户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(@Valid CustomerInfoRequest request) {
        startPage();
        List<CustomerInfoResponse> list = this.customerInfoService.getList(request);
        return getDataTable(list);
    }

    /**
     * 获取客户详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CustomerInfo customerInfo = customerInfoService.getById(id);
        return success(customerInfo);
    }

    /**
     * 新增客户
     */
    @PostMapping
    public AjaxResult add(@RequestBody CustomerInfo customerInfo) {
        return toAjax(customerInfoService.save(customerInfo));
    }

    /**
     * 修改客户
     */
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerInfo customerInfo) {
        customerInfoService.edit(customerInfo);
        return success();
    }

    /**
     * 跟进客户
     */
    @PutMapping("/followCustomer")
    public AjaxResult followCustomer(@RequestBody CustomerRequest request)
    {
        customerInfoService.followCustomer(request);
        return success();
    }

    /**
     * 跟进提醒
     */
    @PutMapping("/followRemind")
    public AjaxResult followRemind(@RequestBody CustomerRequest request)
    {
        customerInfoService.followRemind(request);
        return success();
    }

    /**
     * 跟进还款
     */
    @PutMapping("/followRepayment")
    public AjaxResult followRepayment(@RequestBody CustomerRequest request)
    {
        customerInfoService.followRepayment(request);
        return success();
    }

    /**
     * 认领客户
     */
    @PutMapping("/claimCustomer")
    public AjaxResult insertAuthRole(@RequestBody CustomerRequest request)
    {
        customerInfoService.claimCustomer(request);
        return success();
    }

    /**
     * 分配客户
     */
    @PutMapping("/distCustomer")
    public AjaxResult distCustomer(@RequestBody CustomerRequest request)
    {
        customerInfoService.distCustomer(request);
        return success();
    }

    /**
     * 转售前公共池
     */
    @PutMapping("/publicDist")
    public AjaxResult publicDist(@RequestBody CustomerRequest request)
    {
        customerInfoService.publicDist(request);
        return success();
    }

    /**
     * 客户转后期
     */
    @PutMapping("/stateToLoan")
    public AjaxResult stateToLoan(@RequestBody CustomerRequest request)
    {
        customerInfoService.stateToLoan(request);
        return success();
    }

    /**
     * 分配后期
     */
    @PutMapping("/distLoan")
    public AjaxResult distLoan(@RequestBody CustomerRequest request)
    {
        customerInfoService.distLoan(request);
        return success();
    }

    /**
     * 后期打回
     */
    @PutMapping("/backLoan")
    public AjaxResult backLoan(@RequestBody CustomerRequest request)
    {
        customerInfoService.backLoan(request);
        return success();
    }

    /**
     * 转后期公共池
     */
    @PutMapping("/publicLoan")
    public AjaxResult publicLoan(@RequestBody CustomerRequest request)
    {
        customerInfoService.publicLoan(request);
        return success();
    }

    /**
     * 客户转售后
     */
    @PutMapping("/stateToAfter")
    public AjaxResult stateToAfter(@RequestBody CustomerRequest request)
    {
        customerInfoService.stateToAfter(request);
        return success();
    }

    /**
     * 分配售后
     */
        @PutMapping("/distAfter")
    public AjaxResult distAfter(@RequestBody CustomerRequest request)
    {
        customerInfoService.distAfter(request);
        return success();
    }

    /**
     * 售后打回
     */
    @PutMapping("/backAfter")
    public AjaxResult backAfter(@RequestBody CustomerRequest request)
    {
        customerInfoService.backAfter(request);
        return success();
    }

    /**
     * 转售后公共池
     */
    @PutMapping("/publicAfter")
    public AjaxResult publicAfter(@RequestBody CustomerRequest request)
    {
        customerInfoService.publicAfter(request);
        return success();
    }

    /**
     * 新增客户需求
     */
    @PostMapping("/addNeed")
    public AjaxResult addNeed(@RequestBody CustomerNeed customerNeed) {
        customerInfoService.update(Wrappers.<CustomerInfo>lambdaUpdate()
                .eq(CustomerInfo::getId, customerNeed.getCustomerInfoId())
                .set(CustomerInfo::getAmount, null)
                .set(CustomerInfo::getLoanUse, null)
                .set(CustomerInfo::getLoanRemark, null)
                .set(CustomerInfo::getTimeLimit, null)
                .set(CustomerInfo::getServiceTime, null)
                .set(CustomerInfo::getLendingInstitution, null)
                .set(CustomerInfo::getRepaymentAmount, null)
                .set(CustomerInfo::getDeadline, null)
                .set(CustomerInfo::getUpdateTime, new Date())
                .set(CustomerInfo::getUpdateUser, SecurityUtils.getUserId())
        );

        return toAjax(customerNeedService.save(customerNeed));
    }

    /**
     * 删除客户需求
     */
    @DeleteMapping("/deleteNeed/{id}")
    public AjaxResult deleteNeed(@PathVariable Long id) {
        customerNeedService.removeById(id);
        return success();
    }

    /**
     * 客户需求列表
     */
    @GetMapping("/needList")
    public AjaxResult needList(CustomerNeed customerNeed) {
        Long id = customerNeed.getCustomerInfoId();
        List<CustomerNeed> list = customerNeedService.list(Wrappers.<CustomerNeed>lambdaQuery()
                .eq(CustomerNeed::getCustomerInfoId, id)
                .orderByDesc(CustomerNeed::getId)
        );
        return success(list);
    }

    /**
     * 分配记录列表
     */
    @GetMapping("/allocationList")
    public AjaxResult allocationList(CustomerAllocation customerAllocation) {
        List<CustomerAllocation> list = customerRemarkService.list(Wrappers.<CustomerAllocation>lambdaQuery()
                .lt(ObjectUtil.isNotEmpty(customerAllocation.getId()), CustomerAllocation::getId, customerAllocation.getId())
                .eq(CustomerAllocation::getCustomerInfoId, customerAllocation.getCustomerInfoId())
                .orderByDesc(CustomerAllocation::getId)
                .last("limit 5")
        );

        if (list.size() == 0) {
            return success(list);
        }

        List<Long> userIdList = new ArrayList<>();
        for (CustomerAllocation allocation : list) {
            userIdList.add(allocation.getCreateUser());
            userIdList.add(allocation.getRecipientId());
        }

        Map<Long, String> nickNameMap = sysUserService.getNickNameMap(userIdList);
        list.forEach(item -> {
            // 赋值创作人名称
            item.setOperatorName(nickNameMap.get(item.getCreateUser()));
            // 赋值操作人名称
            item.setRecipientName(nickNameMap.get(item.getRecipientId()));
        });
        return success(list);
    }

    /**
     * 分配记录列表
     */
    @GetMapping("/snapshotList")
    public AjaxResult snapshotList(CustomerSnapshot customerSnapshot) {
        List<CustomerSnapshot> list = customerSnapshotService.list(Wrappers.<CustomerSnapshot>lambdaQuery()
                .lt(ObjectUtil.isNotEmpty(customerSnapshot.getId()), CustomerSnapshot::getId, customerSnapshot.getId())
                .eq(CustomerSnapshot::getCustomerInfoId, customerSnapshot.getCustomerInfoId())
                .orderByDesc(CustomerSnapshot::getId)
                .last("limit 5")
        );

        if (list.size() == 0) {
            return success(list);
        }

        List<Long> userIdList = list.stream().map(CustomerSnapshot::getCustomerInfoId).collect(Collectors.toList());

        Map<Long, String> nickNameMap = sysUserService.getNickNameMap(userIdList);

        list.forEach(item -> item.setNickName(nickNameMap.get(item.getCreateUser())));
        return success(list);
    }

    /**
     * 获取信息列表
     */
    @GetMapping("/getMessageTotal")
    public CustomerFollowResponse getMessageTotal() {
        return this.customerInfoService.getMessageTotal();
    }

    /**
     * 获取用户id列表
     */
    @GetMapping("/getUserList/{type}")
    public AjaxResult getUserList(@PathVariable("type") Integer type) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysUser> list = sysUserService.selectUserList(new SysUser());
        if (!SecurityUtils.isSuperAdmin(loginUser)) {
            List<Long> userIdList = loginUser.getBelongUserIds();
            list.removeIf(t -> {
                boolean flag = true;
                for (Long i : userIdList) {
                    if (i.equals(t.getUserId())) {
                        List<SysRole> sysRoleList = this.sysRoleService.selectRoleListByUserId(t.getUserId());
                        if (!CollectionUtils.isEmpty(sysRoleList)) {
                            String roleKey = String.join("|", sysRoleList.stream().map(SysRole::getRoleKey).collect(Collectors.toList()));
                                switch (type) {
                                    case 1:
                                        flag = roleKey.contains("salesman") ? false : true;
                                        break;
                                    case 5:
                                        flag = roleKey.contains("salesman") ? false : true;
                                        break;
                                    case 6:
                                        flag = roleKey.contains("later_period") ? false : true;
                                        break;
                                    case 7:
                                        flag = roleKey.contains("after_sale") ? false : true;
                                        break;
                                    case 8:
                                        flag = roleKey.contains("later_period") ? false : true;
                                        break;
                                    case 9:
                                        flag = roleKey.contains("after_sale") ? false : true;
                                        break;
                                }
                        } else {
                            flag = true;
                        }
                        break;
                    }
                }
                return flag;
            });
        }
        return success(list);
    }

    /**
     * 获取履历详情
     */
    @GetMapping("/getCustomerSnapshot/{id}")
    public CustomerSnapshot getCustomerSnapshot(@PathVariable Long id) {
        return this.customerSnapshotService.getById(id);
    }

    /**
     * 回滚履历
     */
    @PutMapping("/backCustomerSnapshot")
    public AjaxResult backCustomerSnapshot(@RequestBody CustomerRequest request) {
        this.customerInfoService.backCustomerSnapshot(request);
        return success();
    }



}
